import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Col, Empty, Form, Icon, Input, Row, Typography, message, Select } from 'antd';
import { useRequest, useDictionary, useDynamicList } from '@/hooks';
import FormContainer from './FormContainer';
import styles from './index.less';

const { Text } = Typography;

/**
 * 员工档案 - 语言能力列表
 */
const SkillSection = ({ formData, onChange, readonly, saveAction }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: skillList,
        remove: skillListRemove,
        push: skillListPush,
        getKey: skillListGetKey,
        resetList: skillListReset
    } = useDynamicList([]);
    // 字典数据
    const [skillLevelOptions, getSkillLevelText] = useDictionary('skill_level');

    useEffect(() => {
        // 重置列表的值
        skillListReset(formData.skillList);
    }, [skillListReset, formData.skillList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('skillList', { initialValue: formData.skillList || [] });
    }, [formData.skillList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            employeeCode: formData.employeeCode,
            newList: skillList.map((item, index) => {
                const key = skillListGetKey(index);
                return {
                    employeeCode: formData.employeeCode,
                    skillName: values.skillName[key],
                    proficiency: values.proficiency[key],
                    remarks: values.remarks[key]
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        skillListReset(formData.skillList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (skillList.length === 0) {
            skillListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="专业技能"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className={styles.dynamicList}>
                    {skillList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className={styles.dynamicListContainer}>
                        {skillList.map((item, index) => (
                            <div key={skillListGetKey(index)} className={styles.dynamicListItem}>
                                {editStatus && (
                                    <Icon
                                        onClick={() => skillListRemove(index)}
                                        className={styles.dynamicListClose}
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Row gutter={24}>
                                    <Col span={12}>
                                        <Form.Item label="技能名称">
                                            {editStatus ? (
                                                getFieldDecorator(`skillName[${skillListGetKey(index)}]`, {
                                                    initialValue: item?.skillName ?? undefined,
                                                    rules: [{ max: 50, message: '字数不能超过50个字符' }]
                                                })(<Input maxLength={50} placeholder="请输入" />)
                                            ) : (
                                                <div className="multiLineText">{item?.skillName}</div>
                                            )}
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label="掌握程度（熟练度）">
                                            {editStatus ? (
                                                getFieldDecorator(`proficiency[${skillListGetKey(index)}]`, {
                                                    initialValue: item?.proficiency
                                                        ? Number(item.proficiency)
                                                        : undefined
                                                })(
                                                    <Select placeholder="请选择">
                                                        {skillLevelOptions?.map(option => (
                                                            <Select.Option
                                                                value={Number(option.value)}
                                                                key={option.value}
                                                            >
                                                                {option.text}
                                                            </Select.Option>
                                                        ))}
                                                    </Select>
                                                )
                                            ) : (
                                                <Text>{getSkillLevelText(item?.proficiency?.toString())}</Text>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                                <Row gutter={24}>
                                    <Col span={12}>
                                        <Form.Item label="备注">
                                            {editStatus ? (
                                                getFieldDecorator(`remarks[${skillListGetKey(index)}]`, {
                                                    initialValue: item?.remarks ?? undefined,
                                                    rules: [{ max: 200, message: '字数不能超过200个字符' }]
                                                })(<Input maxLength={200} placeholder="请输入备注" allowClear />)
                                            ) : (
                                                <div className="multiLineText">{item?.remarks}</div>
                                            )}
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </div>
                        ))}
                    </div>
                    {editStatus && skillList.length < 10 ? (
                        <Button style={{ marginTop: '20px' }} block onClick={() => skillListPush({})}>
                            +添加专业技能
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
SkillSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

SkillSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default SkillSection;
